<template>
  <div class="container">
      <div class="card">
          <el-breadcrumb separator="/" class="card-body">
              <el-breadcrumb-item :to="{ path: '/AdminHome' }"><i class="el-icon-location"></i>首页</el-breadcrumb-item>
              <el-breadcrumb-item>{{ this.$route.meta.title }}</el-breadcrumb-item>
          </el-breadcrumb>
      </div>
      <div class="card clearfix">
          <div class="classfy-tree" :style="{ height: cardBodyHeight + 'px' }">
              <div class="card-header">
                  组织结构 :
                  <div class="f-right">
                      <el-button type="text" icon="el-icon-plus" @click="add">添加</el-button>
                  </div>
              </div>
              <el-tree :data="treeData" :props="defaultProps" @node-click="clickTree" default-expand-all></el-tree>
          </div>
          <div class="classfy-data" ref="tabBody">
              <div class="card-header">
                  <h2 class="e_inner_text f-left">{{ groupName }}</h2>
              </div>
              <div class="card-body">
                  <div class="clearfix" style="float:left;width:100%;">
                      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                          <div class="info-ruleForm">
                              <el-form-item label="组织编码">
                                  <el-input v-model="form.code" disabled placeholder="获取组织编码失败,请刷新页面"></el-input>
                              </el-form-item>
                              <el-form-item label="组织名称" prop="label">
                                  <el-input v-model.lazy="form.label" placeholder="获取组织名称失败,请刷新页面"></el-input>
                              </el-form-item>
                              <el-form-item label="所属上级">
                                  <el-input v-model="form.parentLabel" disabled placeholder="暂无上级"></el-input>
                              </el-form-item>
                              <el-form-item label="设置部门责任人" prop="chargeUsers">
                                  <input v-model="form.chargeUsers" disabled hidden>
                                  <div class="setPosition">
                                      <span v-for="(p,index) in userTreeData" :key="p.index">{{ p.name }}<i class="el-icon-close" @click="delPosition(index)"></i></span>
                                  </div>
                                  <el-button type="text" size="medium" class="el-query-tree" @click="$tree('查找责任人','czzrr')">查找</el-button>
                              </el-form-item>
                          </div>
                          <hr>
                          <div class="info-ruleForm">
                              <el-form-item>
                                  <el-button type="primary" @click="onSubmit('form')">保存</el-button>
                                  <el-button @click="del(form.id)">删除该组织</el-button>
                              </el-form-item>
                          </div>
                      </el-form>
                  </div>
              </div>
          </div>
      </div>
      
  </div>
</template>

<script>
import request from "@/utils/request";
export default {
  name: "DepartmentManagement",
  data() {
    return {
      groupName: "-",
      dialogVisible: false,
      form: {
        id:"",
        label: "",
        code: "",
        parentLabel: "",
        parentId: "",
        chargeUsers: ""
      },
      rules: {
        label: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ]
      },
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
        treeId: ""
      }
    };
  },
  methods: {
    add() {
      this.$router.push({
        path: "/SystemSetting/Groups/add"
      });
    },
    updateClassification(id) {
      this.$router.push({
        path: "/SystemSetting/Classification/update" + "?id=" + id
      });
    },
    createClassification(id) {
      this.$router.push({
        path: "/SystemSetting/Classification/create"
      });
    },
    delThis(id) {
      this.$confirm("确认删除这个组织？")
        .then(_ => {
          assID();
        })
        .catch(_ => {});
    },
    clickTree(data) {
      //通过ID刷新右边分类数据
      console.warn(data)
      this.form.id = data.id;
      this.form.label = data.label;
      this.form.code = data.code;
      this.form.parentLabel = data.parentLabel;
      this.form.parentId = data.parentId;
      this.groupName  = data.label;
      request({
        url: this.$api.getDepartment + "?id=" + data.id,
        method: "get"
      }).then(res => {
        
        this.form.chargeUsers = res.data.chargeUsers;
      });
      request({
        url: this.$api.getDepartment + "?id=" + data.parentId,
        method: "get"
      }).then(res => {
        console.log(res.data)
        if(res.data){
          this.form.parentLabel = res.data.label;
        }
      });
    },
    onSubmit(formName) {
      let chargeUsers = [];
      for(let user of this.form.chargeUsers){
        let userItem  = {
          name:user.name,
          id:user.userId
        }
        chargeUsers.push(userItem)
      }
      this.form.chargeUsers = chargeUsers;
      let data = this.form;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.chargeUsers == "") {
            this.$message.error("至少设置一个部门责任人");
          } else {
            request({
              url: this.$api.updateDepartment,
              method: "post",
              data: data
            }).then(res => {
              //判断成功
              if (res.code !== "000000") {
                this.$message.error(res.msg);
              } else {
                this.$message.success("修改成功!");
                // window.location.reload();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    delPosition(i) {
      //删除该部门负责人
      let chargeUsersData = this.form.chargeUsers;
      chargeUsersData.splice(i, 1); //删除数组中下标为 i 的元素
      this.form.chargeUsers = chargeUsersData;
    },
    //获取组织树形数据
    getTree() {
      request({
        url: this.$api.getAllDepartment,
        method: "get"
      }).then(res => {
        this.treeData = res.data;
        this.groupName = this.form.label = res.data[0].label;

        this.form.code = res.data[0].code;
        this.form.parentLabel = res.data[0].parentLabel;
        this.form.id = res.data[0].id;
        this.form.parentId = res.data[0].parentId;
        request({
          url: this.$api.getDepartment + "?id=" + res.data[0].id,
          method: "get"
        }).then(res => {
          this.form.chargeUsers = res.data.chargeUsers;
        });
      });
    },
    del(id) {
      this.$confirm("确认删除这个组织？")
        .then(_ => {
          console.log("确定"+_);
        request({
          url: this.$api.deleteDepartment + "?id=" + this.form.id,
          method: "get"
        }).then(res => {
          //删除提醒
          console.log(res);
          if(res.code !== '000000'){
            this.$message.warn(res.msg);
          }else{
            this.$message.success("删除成功!");
            window.location.reload();
          }
        });
        })
        .catch(_ => {
          console.log("取消删除"+_);
        });
    },
  },
  mounted() {
    //初始化数据
    this.getTree();
  },
  computed: {
    cardBodyHeight: function() {
      let boxHeight = window.innerHeight - 149;
      return boxHeight;
    },
    userTreeData:function () {
      if(this.$store.getters.userTreeData !== ''){
       return this.form.chargeUsers = this.$store.getters.userTreeData; 
      }else{
        return this.form.chargeUsers;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.classfy-tree {
  width: 220px;
  float: left;
  position: relative;
  z-index: 1;
  background: #f9fafc;
  border-right: 1px solid #ebeef5;
  .card-header {
    border-bottom: 1px solid #e4e6e9;
  }
  .el-tree {
    padding: 10px;
    background: transparent !important;
  }
}

.el-tree-node:focus > .el-tree-node__content {
  background-color: #4674d6 !important;
}

.el-tree-node__content:hover {
  background-color: #ddd;
}

.classfy-data {
  padding-left: 221px;
  position: relative;
  z-index: 0;
  .card-header {
    line-height: 51px;
    height: 54px;
  }
  .e_inner_text {
    color: #000;
    font-size: 18px;
    line-height: 54px;
  }
}

.info-ruleForm {
  margin: 0 auto;
}

.setPosition {
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  min-height: 60px;
  border: 1px solid #dcdfe6;
  padding: 0 10px;
  span {
    background: #f9f9f9;
    padding: 3px;
    margin-right: 10px;
    margin-top: 5px;
    border-radius: 30px;
    display: inline-block;
    line-height: 1;
    .el-icon-close {
      font-size: 12px;
      margin-left: 5px;
      margin-right: 4px;
      background: #ddd;
      padding: 1px;
      cursor: pointer;
      border-radius: 10px;
      color: #000;
    }
    .el-icon-close:hover {
      background: @theme;
      color: #fff;
    }
  }
}
</style>